package com.zhudi.excel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.google.gson.Gson;
import com.zhudi.excel.listener.GenericExcelListener;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class ExcelUtils {

    public static<T> List<T> readOneSheet(String path,Class<T> type){
        // 这里默认每次会读取100条数据 然后返回过来 直接调用使用数据就行
        // 具体需要返回多少行可以在`PageReadListener`的构造函数设置
        Gson gson = new Gson();
        List<T> result = new ArrayList<>();
        EasyExcel.read(path, type, new PageReadListener<T>(dataList -> {
            for (T demoData : dataList) {
                result.add(demoData);
                log.info("读取到一条数据{}", gson.toJson(demoData));
            }
        })).sheet().doRead();
        return result;
    }

    public static List<List<Object>> readMultipleSheets(String fileName){
        List<List<Object>> allDataList = new ArrayList<>();

        EasyExcel.read(fileName).autoCloseStream(Boolean.TRUE).registerReadListener(new GenericExcelListener<>()).doReadAll();

        return allDataList;
    }
}
